package com.si.store;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.si.store.adapter.AdapterApp;
import com.si.store.model.GamesAndApps;
//import android.util.Log;

public class FragmentApp extends Fragment {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";
	GridView gridview;
	Context context;
	List<GamesAndApps> listApp;
	AdapterApp adapter;
	static boolean in;
	static int index;

	// private static int position;

	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static FragmentApp newInstance(int sectionNumber) {
		FragmentApp fragment = new FragmentApp();
		Bundle args = new Bundle();

		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;

	}

	public FragmentApp() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_app, container,
				false);
		context = rootView.getContext();
		listApp = new ArrayList<GamesAndApps>();

		getData();
		randomApp(listApp);
		gridview = (GridView) rootView.findViewById(R.id.gridView_app);

		adapter = new AdapterApp(context, R.layout.item_app, listApp);
		gridview.setAdapter(adapter);

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				index = position;
				AlertDialog.Builder b = new AlertDialog.Builder(context);
				b.setIcon(listApp.get(position).getImg());
				b.setTitle(listApp.get(position).getDowlaod());
				b.setPositiveButton("Download",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// new TaskData().execute();
								actionDownload(index);
							}
						});
				b.setNeutralButton("Email",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								sengmail();
							}
						});

				b.setNegativeButton("Share",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Share();
							}
						});
				b.create().show();
			}
		});
		return rootView;
	}

	private void getData() {
		listApp.add(new GamesAndApps(R.drawable.ic_city_rider, "City Rider", "http://bit.ly/1pO1R5p"));
		listApp.add(new GamesAndApps(R.drawable.ic_climbing_sand_dune, "Climbing Sand Dune 3D", "http://bit.ly/1pO2mMW"));
		listApp.add(new GamesAndApps(R.drawable.ic_id_devices, "ID Devices", "http://bit.ly/1pO2zzC"));
		listApp.add(new GamesAndApps(R.drawable.ic_hd_video_download, "HDVideoDownloader", "http://bit.ly/1pO2YSC"));
		listApp.add(new GamesAndApps(R.drawable.ic_mega_casino_bingo, "Mega Casino Bingo", "http://bit.ly/1pO3sIq"));
		listApp.add(new GamesAndApps(R.drawable.ic_candy_of_lang, "Candy of Legends", "http://bit.ly/1pO3Syp"));
		listApp.add(new GamesAndApps(R.drawable.ic_candy_eg, "Candy Egg Blast", "http://bit.ly/1uYXOKt"));
		listApp.add(new GamesAndApps(R.drawable.ic_city_rider_new, "City Rider New", "http://bit.ly/1pO4u7b"));
		listApp.add(new GamesAndApps(R.drawable.ic_cut_the_cooke, "Cut the Cookie", "http://bit.ly/1uYYXlg"));
		listApp.add(new GamesAndApps(R.drawable.ic_endless_runner, "Endless Runner", "http://bit.ly/1uYZ5Be"));
		listApp.add(new GamesAndApps(R.drawable.ic_jetpack_pig, "Jetpack Pig", "http://bit.ly/1pO58Sd"));
		listApp.add(new GamesAndApps(R.drawable.ic_swing_copters, "Swing Copters", "http://bit.ly/1pO5yrN"));
		listApp.add(new GamesAndApps(R.drawable.ic_music_search, "Music Search", "http://bit.ly/1uZ0jfN"));
		listApp.add(new GamesAndApps(R.drawable.ic_quickie_cam, "Quickie Cam", "http://bit.ly/1pO67So"));
		listApp.add(new GamesAndApps(R.drawable.ic_quick_math, "Quick Maths", "http://bit.ly/1pO6pJ0"));
		listApp.add(new GamesAndApps(R.drawable.ic_racing_car, "Racing Car", "http://bit.ly/1uZ13Se"));
		listApp.add(new GamesAndApps(R.drawable.ic_samozai, "Samurai Fight And Run", "http://bit.ly/1pO73Gg"));
		listApp.add(new GamesAndApps(R.drawable.ic_treasure_match, "Treasure Match Pyramid Quest", "http://bit.ly/1uZ1Qm5"));
		listApp.add(new GamesAndApps(R.drawable.ic_casino_slost, "Vegas Casino Slot Machine", "http://bit.ly/1uZ1VGr"));
		listApp.add(new GamesAndApps(R.drawable.ic_xray_scanner, "Xray Scanner", "http://bit.ly/1uZ20Ki"));
		listApp.add(new GamesAndApps(R.drawable.ic_treasure, "Treasure MatchPyramid Quest", "http://bit.ly/1pO7XCV"));
		listApp.add(new GamesAndApps(R.drawable.ic_zombles, "Walking Zombies", "http://bit.ly/1uZ2H6m"));
		listApp.add(new GamesAndApps(R.drawable.ic_flowfrenzy, "FLOW FRENZY", "http://bit.ly/1uZ32FW"));
		listApp.add(new GamesAndApps(R.drawable.ic_angry_jungle,"Angry Jungle Kid Jump And Run", "http://bit.ly/1uZ3ynr"));
		listApp.add(new GamesAndApps(R.drawable.ic_photo, "Photo Text Editor","http://bit.ly/1pO94Cv"));
		listApp.add(new GamesAndApps(R.drawable.ic_fruits_link, "Fruits Link", "http://bit.ly/1uZ4599"));
		listApp.add(new GamesAndApps(R.drawable.ic_mp3_music_playe, "MP3 Music Player", "http://bit.ly/1uZ4Bnn"));
		listApp.add(new GamesAndApps(R.drawable.ic_gangnam_fly_surfers, "Gangnam Fly Surfers", "http://bit.ly/1uZ4ZCl"));
		listApp.add(new GamesAndApps(R.drawable.ic_smart_photo, "Smart Photo Editor", "http://bit.ly/1pOan4c"));
		listApp.add(new GamesAndApps(R.drawable.ic_transpares, "Transparent Screen", "http://bit.ly/1s8qZJ3"));
		listApp.add(new GamesAndApps(R.drawable.ic_2048, "2048", "http://bit.ly/ZtCcID"));
		listApp.add(new GamesAndApps(R.drawable.ic_candy_blast_free, "Candy Blast Free", "http://bit.ly/ZtCsaA"));
		listApp.add(new GamesAndApps(R.drawable.ic_candy_egg_blast, "Candy Egg Blast", "http://bit.ly/ZtCyz2"));
		listApp.add(new GamesAndApps(R.drawable.ic_kids_memory, "Kids Memory", "http://bit.ly/ZtCzmt"));
		listApp.add(new GamesAndApps(R.drawable.ic_kungfu_panda_jum, "Kungfu Panda Jump", "http://bit.ly/ZtCAa4"));
		listApp.add(new GamesAndApps(R.drawable.ic_mp3_music_playe_free, "MP3 Music Player FREE", "http://bit.ly/1EwLpjI"));
		listApp.add(new GamesAndApps(R.drawable.one_piece_funny, "One Piece Funny", "http://bit.ly/1EwLvIn"));
		listApp.add(new GamesAndApps(R.drawable.racing_car, "Racing Car", "http://bit.ly/1EwLEeL"));
		listApp.add(new GamesAndApps(R.drawable.samurai_fught_run, "Samurai Fight and Run", "http://bit.ly/ZtCQFZ"));
		listApp.add(new GamesAndApps(R.drawable.samurai_run, "Samurai Run", "http://bit.ly/1EwMlVr"));
		listApp.add(new GamesAndApps(R.drawable.ic_music_free, "Music Free", "http://bit.ly/1EwMoQW"));
		listApp.add(new GamesAndApps(R.drawable.ic_crazy_bird, "Crazy Bird", "http://bit.ly/ZtCZZZ"));
		listApp.add(new GamesAndApps(R.drawable.candy_crush_saga, "Candy Crush Saga", "http://bit.ly/ZRYVPx"));
		listApp.add(new GamesAndApps(R.drawable.christmas_memory, "Christmas Memory", "http://bit.ly/1qnV9lW"));
		listApp.add(new GamesAndApps(R.drawable.pluzzle2048, "2048 Puzzle", "http://bit.ly/1tgAqZ1"));
		listApp.add(new GamesAndApps(R.drawable.alien_bird, "Alien Bird", "http://bit.ly/ZxMtDD"));
		listApp.add(new GamesAndApps(R.drawable.angry_bee, "Angry Bee", "http://bit.ly/1tgF5u7"));
		listApp.add(new GamesAndApps(R.drawable.mega_casino_bingo, "Mega Casino Bingo", "http://bit.ly/1tgFBrQ"));
		listApp.add(new GamesAndApps(R.drawable.brazil_wc2014, "Brazil WC 2014", "http://bit.ly/1tgH3L0"));
		listApp.add(new GamesAndApps(R.drawable.timber_man, "Timber Man", "http://bit.ly/1rkt1QM"));
		listApp.add(new GamesAndApps(R.drawable.wrecking_rob, "Wrecking Rob", "http://bit.ly/1vW1HP6"));
		listApp.add(new GamesAndApps(R.drawable.gangnam_fly_surfers, "Gangnam Fly Surfers", "http://bit.ly/1z2IZcs"));
		listApp.add(new GamesAndApps(R.drawable.guess_the_pic, "Guess The Pic", "http://bit.ly/1z62xfW"));
		listApp.add(new GamesAndApps(R.drawable.happy_brid, "Happy Bird", "http://bit.ly/1z64nxy"));
		listApp.add(new GamesAndApps(R.drawable.jewels_fruits, "Jewels Fruits", "http://bit.ly/1z65T2B"));
	}

	DownloadManager mgr;
	Cursor cursor;

	// downlaod and intasll apk in android mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
	private void actionDownload(int position) {

		try {
			String dir = Environment.getExternalStorageDirectory() + "/"
					+ getString(R.string.App_games);
			String url = listApp.get(position).getLink();
//			Log.e("link", url);
			File direct = new File(dir);
			if (!direct.exists()) {
				direct.mkdirs();
			}
			mgr = (DownloadManager) context
					.getSystemService(Context.DOWNLOAD_SERVICE);
			Uri downloadUri = Uri.parse(url);
			DownloadManager.Request request = new DownloadManager.Request(
					downloadUri);
			String title = new File(listApp.get(position).getDowlaod())
					.getName() + ".apk";
			Toast.makeText(context, dir + "/" + title, Toast.LENGTH_SHORT)
					.show();
			request.setAllowedNetworkTypes(
					DownloadManager.Request.NETWORK_WIFI
							| DownloadManager.Request.NETWORK_MOBILE)
					.setAllowedOverRoaming(false).setTitle(title)
					.setDescription(title)
					.setDestinationInExternalPublicDir("/", title);
			mgr.enqueue(request);
			cursor = mgr.query(new DownloadManager.Query());
			context.registerReceiver(onComplete, new IntentFilter(
					DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	BroadcastReceiver onComplete = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			InstallApplication();
		}
	};
	public void InstallApplication() {
		String _strAPKPath = Environment.getExternalStorageDirectory() + "/"
				+ listApp.get(index).getDowlaod() + ".apk";
		String type = "application/vnd.android.package-archive";
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(_strAPKPath)), type);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	// sen gmail in android Mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
	public void sengmail() {

		Intent intent = new Intent(Intent.ACTION_SEND);
		String subject = listApp.get(index).getLink();
		String text = listApp.get(index).getDowlaod();
		intent.putExtra(Intent.EXTRA_EMAIL, "sinv_b01317@fpt.aptech.ac.vn");
		intent.putExtra(Intent.EXTRA_SUBJECT, "Pleas... Install and play app. Help me ");
		intent.putExtra(Intent.EXTRA_TEXT, text + ":" + subject);
		intent.setType("image/png");
		try {
		    startActivity(Intent.createChooser(intent, "Send Email..."));
		} catch (android.content.ActivityNotFoundException ex) {
		    Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
		}
	}

	// share facebook mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
	private void Share() {
		Intent shareIntent = new Intent(Intent.ACTION_VIEW);
		shareIntent.setType("");
		shareIntent.putExtra(Intent.EXTRA_TITLE, "");
		shareIntent
				.putExtra(Intent.EXTRA_TEXT,
						"https://play.google.com/store/apps/details?id=com.facebook.katana");
		shareIntent.putExtra(Intent.EXTRA_SUBJECT, "");
		PackageManager manager = getActivity().getPackageManager();
		List<ResolveInfo> list = manager.queryIntentActivities(shareIntent, 0);
		for (final ResolveInfo app : list) {
			Intent tagertshare = new Intent(Intent.ACTION_VIEW);
			tagertshare.setType("");
			if ((app.activityInfo.name).contains("facebook")) {
				final ActivityInfo activity = app.activityInfo;
				final ComponentName name = new ComponentName(
						activity.applicationInfo.packageName, activity.name);
				shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
				shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				shareIntent.setComponent(name);
				startActivity(shareIntent);
			}
		}
	}

	// random icon trong girdView
	private List<GamesAndApps> randomApp(List<GamesAndApps> lApps) {
		Collections.shuffle(lApps);
		return lApps;
	}

}
